#!/bin/bash

db=$1
tmpDB="temp-$db"

hostIP=192.168.31.211
port=3306
uname=dba
passwd=Admin_123

if [ "$1" == "" ];then
  echo "useage: $0 dbname tablename ..."
  exit 1;
fi

filedate="$(date +%y%m%d)_$db"
# 导表结构
filename=$filedate.sql
echo "==> export db: $db"
mysqldump --no-data -u$uname -p$passwd -h$hostIP  -P$port $db > $filename

# 对比结构
# mysql -u$uname -p$passwd -h$hostIP  -P$port --execute="drop database if exists $tmpDB;"
# mysql -u$uname -p$passwd -h$hostIP  -P$port --execute="CREATE DATABASE \`$tmpDB\` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci if not exists $tmpDB;"
# mysqldbcompare --server1=$uname:$passwd@$hostIP --server2=$uname:$passwd@$hostIP --difftype=sql \`$db\`:\`$tmpDB\`
update_filename="$filedate"_update.sql
echo "==> diff db: $db, $tmpDB"
mysqldiff --force --server1=$uname:$passwd@$hostIP --difftype=sql  \`$tmpDB\`:\`$db\`|grep -v '^[#@-+]' > $update_filename

if [ "$(cat $update_filename|grep '^Success.')" != "" ];then
  echo "==> differences Success. All objects are the same."
  rm -f $update_filename
else
  echo "==> differences found."; cat $update_filename
  tables=`cat $update_filename|grep 'TABLE:'|awk '{print $3}'`
  if [ "$tables" != "" ];then
    echo "==> new tables: $tables"
    echo "---------new table--------" >>  $update_filename
    mysqldump --no-data -u$uname -p$passwd -h$hostIP  -P$port $db $tables >> $update_filename 
  fi
fi

# 升级表
mysql -u$uname -p$passwd -h$hostIP -P$port -C $tmpDB < $filename

# 导表数据
if [ "$2" != "" ];then
  init_filename="$filedate"_init.sql

  echo "==> export tables: $2"
  mysqldump --no-create-info -u$uname -p$passwd -h$hostIP  -P$port $@ > $init_filename
  sed -i 's/^INSERT/REPLACE/' $init_filename
  mysql -u$uname -p$passwd -h$hostIP -P$port -C $tmpDB < $init_filename
fi
